<?php

namespace Home\Controller;

use Think\Controller;

class WechatHelperController extends Controller {

    var $appid = "";
    var $appsecret = "";
    var $access_token = "";
    var $lasttime = "";

//构造函数，获取Access Token
    public function __construct($PublicCodeID = 0, $refer = FALSE) {
        load('@.HttpHelper');
        $publicCodeModel = M('publiccode');
        $publicCodeCondition['ID'] = 1;
        $result = $publicCodeModel->where($publicCodeCondition)->find();
        if (count($result) == 0) {
            return "";
        } else {
            $this->appid = $result["AppID"];
            $this->appsecret = $result["Secret"];
        }
        $accessTokenModel = M('accesstoken');
        $accessTokenCondition['PublicCodeID'] = $PublicCodeID;
        $result = $accessTokenModel->where($accessTokenCondition)->find();
        if (count($result) == 0 || time() > ($result["UpdateTime"] + 7200) || $refer) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;
            $res = \HttpHelper::https_request($url);
            $at_result = json_decode($res, true);
            $this->access_token = $at_result["access_token"];
            $this->lasttime = time();
            $model = M('accesstoken');
            $data['AccessToken'] = $this->access_token;
            $data['UpdateTime'] = $this->lasttime;
            if (count($result) == 0 && !$refer) {
                $addresult = $model->data($data)->add();
            } else {
                $updateresult = $model->where('PublicCodeID=' . $PublicCodeID)->save($data);
            }
        } else {
            $this->access_token = $result["AccessToken"];
            $this->lasttime = $result["UpdateTime"];
        }
    }

//获取关注者列表
    public function get_user_list($next_openid = NULL) {
        load('@.HttpHelper');
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . $this->access_token . "&next_openid=" . $next_openid;
        $res = \HttpHelper::https_request($url);
        return json_decode($res, true);
    }

//获取用户基本信息
    public function get_user_info($openid) {
        load('@.HttpHelper');
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->access_token . "&openid=" . $openid . "&lang=zh_CN";
        $res = \HttpHelper::https_request($url);
        return json_decode($res, true);
    }

//创建菜单
    public function create_menu($data) {
        load('@.HttpHelper');
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $this->access_token;
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

//发送客服消息，已实现发送文本，其他类型可扩展
    public function send_custom_message($touser, $type, $data) {
        load('@.HttpHelper');
        $msg = array('touser' => $touser);
        switch ($type) {
            case 'text':
                $msg['msgtype'] = 'text';
                $msg['text'] = array('content' => urlencode($data));
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $this->access_token;
        return \HttpHelper::https_request($url, urldecode(json_encode($msg)));
    }

//生成参数二维码
    public function create_qrcode($scene_type, $scene_id) {
        load('@.HttpHelper');
        switch ($scene_type) {
            case 'QR_LIMIT_SCENE': //永久
                $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": ' . $scene_id . '}}}';
                break;
            case 'QR_SCENE':       //临时
                $data = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $scene_id . '}}}';
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $this->access_token;
        $res = \HttpHelper::https_request($url, $data);
        $result = json_decode($res, true);
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($result["ticket"]);
    }

//创建分组
    public function create_group($name) {
        load('@.HttpHelper');
        $data = '{"group": {"name": "' . $name . '"}}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=" . $this->access_token;
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

//移动用户分组
    public function update_group($openid, $to_groupid) {
        load('@.HttpHelper');
        $data = '{"openid":"' . $openid . '","to_groupid":' . $to_groupid . '}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" . $this->access_token;
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

    //获取用户所在组
    public function get_user_group($openid) {
        //https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=ACCESS_TOKEN
        load('@.HttpHelper');
        $data = '{"openid":"' . $openid . '"}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=" . $this->access_token;
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

    //获取所有分组
    public function get_group() {
        load('@.HttpHelper');
        $url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" . $this->access_token;
        $res = \HttpHelper::https_request($url);
        return json_decode($res, true);
    }

    //修改组名
    public function update_groupName($groupid, $groupName) {
        load('@.HttpHelper');
        $url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_TOKEN" . $this->access_token;
        $data = sprintf("{\"group\":{\"id\":%s,\"name\":\"%s\"}}", $groupid, $groupName);
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

//上传多媒体文件
    public function upload_media($type, $file) {
        load('@.HttpHelper');
        echo " 图片路径-->" . $_SERVER['DOCUMENT_ROOT'] . "/" . $file;
        $data = array("media" => "@" . $_SERVER['DOCUMENT_ROOT'] . "/" . $file);
//        $data = array("media" => "@" . __FILEPATH__ . $file);
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $this->access_token . "&type=" . $type;
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

    //上传图文消息
    /**
     * 参数	是否必须	说明
      Articles	 是	 图文消息，一个图文消息支持1到10条图文
      thumb_media_id	 是	 图文消息缩略图的media_id，可以在基础支持-上传多媒体文件接口中获得
      author	 否	 图文消息的作者
      title	 是	 图文消息的标题
      content_source_url	 否	 在图文消息页面点击“阅读原文”后的页面
      content	 是	 图文消息页面的内容，支持HTML标签
      digest	 否	 图文消息的描述
      show_cover_pic	 否	 是否显示封面，1为显示，0为不显示
     * "author" => $author,
      "title" => $title,
      "content_source_url" => $content_source_url,
      "content" => $content,
      "digest" => $digest,
      "show_cover_pic" => $show_cover_pic
     */

    /**
     * 
     * @param type $type npnews
     * @param type $author 作者
     * @param type $title 标题
     * @param type $content_source_url 阅读原文URL
     * @param type $content 正文
     * @param type $digest 图文消息的描述
     * @param type $show_cover_pic 是否显示封面
     * @param type $thumb_media_id 图文消息缩略图的media_id
     * @return type 
     */
    public function upload_mpnews($datanews) {
        load('@.HttpHelper');
        $url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" . $this->access_token;
        $data = json_encode($datanews, JSON_UNESCAPED_UNICODE);
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

    //群发视频消息时获取视频ID
    public function upload_video($media_id, $title, $description) {
        load('@.HttpHelper');
        $data = array("media_id" => $media_id, "title" => $title, "description" => $description);
        $url = "https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token=" . $this->access_token;
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

    //查询微信菜单
    public function get_menu() {
        load('@.HttpHelper');
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $this->access_token;
        $res = \HttpHelper::https_request($url);
        return json_decode($res, true);
    }

    public function Send_Message($type, $data) {
        load('@.HttpHelper');
        $url;
        switch ($type) {
            case '1':
                $url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=" . $this->access_token;
                break;
            case '2':
                $url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" . $this->access_token;
                break;
            default:
                break;
        }
        $res = \HttpHelper::https_request($url, $data);
        return json_decode($res, true);
    }

}
